<template>
  <a-spin :spinning="spinning" class="page-miH">
    <TableTitle v-if="mode === 'company'" style="padding: 0; height: 32px; line-height: 32px; margin: 4px 0 16px">
      <template slot="title">签署记录</template>
      <template slot="action">
        <a-button :disabled="!selectedRowKeys.length" @click="deleteContract()">批量删除</a-button>
      </template>
    </TableTitle>
    <div class="contract-wrapper">
      <SummaryBarAll v-if="mode === 'company'" ref="summaryBar" :selectTypeIndex="selectTypeIndex" @typeChange="selectFunc" />
      <TableBody
        selectHead
        selection
        :tableName="mode === 'overview' ? 'allContractOV' : 'allContract'"
        :selectedHead.sync="selectedHead"
        :selectedRowKeys.sync="selectedRowKeys"
        :source="contractList"
        :headerRowID="'sortable_list'"
        :columns="columns"
        :class="mode === 'company' ? 'mt24' : ''"
        @onClose="() => {}"
        @onSearch="selectFunc()"
        @onReload="selectFunc(selectTypeIndex)"
        @onExport="() => selectDownloadType(1)"
        @onExportAll="() => selectDownloadType(2)"
      >
        <template slot="search">
          <a-input-search
            v-model="contractNameOrNoOrSignNo"
            :allowClear="true"
            placeholder="姓名/手机号/合同名称"
            style="width: 220px"
            @search="searchContract"
          />
          <a-select
            v-if="mode === 'overview'"
            v-model="selectTypeIndex"
            placeholder="请选择合同状态"
            style="width: 200px"
            @select="selectFunc"
          >
            <a-select-option :value="1">全部合同</a-select-option>
            <a-select-option :value="2">即将到期</a-select-option>
            <a-select-option :value="3">已到期且未续签</a-select-option>
            <a-select-option :value="4">单人合同大于等于两份</a-select-option>
          </a-select>
          <template v-if="mode === 'company'">
            <a-select v-model="fileType" :allowClear="true" placeholder="请选择合同类型" style="width: 200px" @change="searchContract">
              <a-select-option v-for="item in enumerateList" :key="item.value" :value="item.value">
                {{ item.name }}
              </a-select-option>
            </a-select>
            <a-select v-model="empStatus" :allowClear="true" placeholder="请选择员工状态" style="width: 200px" @change="searchContract">
              <a-select-option value="1">待入职</a-select-option>
              <a-select-option value="2">在职</a-select-option>
              <a-select-option value="3">待离职</a-select-option>
              <a-select-option value="4">离职</a-select-option>
            </a-select>
          </template>
          <template v-else>
            <a-select v-model="fileType" :allowClear="true" label="合同类型" placeholder="请选择合同类型" style="width: 200px">
              <a-select-option v-for="item in enumerateList" :key="item.value" :value="item.value">
                {{ item.name }}
              </a-select-option>
            </a-select>
            <a-select v-model="empStatus" :allowClear="true" label="员工状态" placeholder="请选择员工状态" style="width: 200px">
              <a-select-option value="1">待入职</a-select-option>
              <a-select-option value="2">在职</a-select-option>
              <a-select-option value="3">待离职</a-select-option>
              <a-select-option value="4">离职</a-select-option>
            </a-select>
          </template>
          <a-input-search v-model="idCard" label="身份证号" :allowClear="true" placeholder="身份证号" />
          <a-select
            v-if="mode === 'overview'"
            v-model="tempSubject"
            :allowClear="true"
            label="用工单位"
            placeholder="请选择用工单位"
            style="width: 200px"
          >
            <a-select-option v-for="(subItem, index) in tempSubjectOptions" :key="index" :value="subItem.value">
              {{ subItem.label }}
            </a-select-option>
          </a-select>
          <a-range-picker
            v-model="publishDateRange"
            :allowClear="true"
            :placeholder="['合同开始时间', '合同开始时间']"
            label="合同开始时间"
            format="YYYY-MM-DD"
            style="width: 240px"
          >
            <a-icon slot="suffixIcon" type="clock-circle" />
          </a-range-picker>
          <a-range-picker
            v-model="endDateRange"
            :allowClear="true"
            :placeholder="['合同结束时间', '合同结束时间']"
            label="合同结束时间"
            format="YYYY-MM-DD"
            style="width: 240px"
          >
            <a-icon slot="suffixIcon" type="clock-circle" />
          </a-range-picker>
          <a-range-picker
            v-model="signFinishDateRange"
            :allowClear="true"
            :placeholder="['合同签署完成时间', '合同签署完成时间']"
            label="合同签署完成时间"
            format="YYYY-MM-DD"
            style="width: 320px"
          >
            <a-icon slot="suffixIcon" type="clock-circle" />
          </a-range-picker>
        </template>
        <template slot-scope="prop">
          <a-table
            :class="prop.className"
            :components="prop.components"
            :columns="prop.columns"
            :scroll="{ x: prop.scrollWidth }"
            :customHeaderRow="
              () => {
                return {
                  domProps: {
                    id: prop.headerRowID
                  }
                };
              }
            "
            :data-source="contractList"
            row-key="id"
            :row-selection="{
              selectedRowKeys: selectedRowKeys,
              onChange: onSelectChange
            }"
            :pagination="pagination"
            @change="handleTableChange"
          >
            <span slot="conType" slot-scope="text">{{ customRenderContractType(text) }}</span>
            <span slot="startDate" slot-scope="text">{{ customRenderMoment(text) }}</span>
            <span slot="endDate" slot-scope="text">{{ customRenderMoment(text) }}</span>
            <span slot="signFinishDate" slot-scope="text">{{ customRenderMoment(text) }}</span>
            <span slot="conRemark" slot-scope="text">
              <a-tooltip placement="bottom">
                <template slot="title" v-if="text">
                  <span>{{ text }}</span>
                </template>
                <div class="contractNoOver">{{ text ? text : "--" }}</div>
              </a-tooltip>
            </span>
            <span slot="isEntity" slot-scope="text">
              {{ text ? "纸质合同" : "电子合同" }}
            </span>
            <span slot="remainingValidTime" slot-scope="text">
              <span :class="text === 3 ? 'color2294FF' : text === 2 ? 'colorFAC04A' : 'colorC0C0C0'">
                <a-icon
                  v-if="text <= 30 && text >= 0 && text !== null"
                  type="exclamation-circle"
                  :style="{ fontSize: '16px', color: '#FA5051' }"
                />
              </span>
              <span :style="text <= 30 && text >= 0 && text !== null ? 'color: #FA5051' : ''" v-if="text >= 0 && text !== null"
                >{{ text }} 天</span
              >
              <span v-else-if="text === null" style="color: #909090">--</span>
              <span v-else style="color: #909090">已到期</span>
            </span>
            <span slot="action" slot-scope="text, record">
              <span class="flex-center">
                <a
                  v-if="record.isEntity"
                  class="edit"
                  type="link"
                  :style="{ color: record.filePath ? 'var(--primary)' : '#ddd' }"
                  :disabled="!record.filePath"
                  @click="downloadContract(record)"
                  >下载</a
                >
                <a v-else class="edit" type="link" @click="check(record)">预览</a>
              </span>
            </span>
          </a-table>
        </template>
      </TableBody>
      <!-- 预览合同 -->
      <a-modal
        title="预览"
        :confirm-loading="confirmLoading"
        :visible="detailVisible"
        width="800px"
        @ok="(detailVisible = false), (eleContractDetailShow = false)"
        @cancel="(detailVisible = false), (eleContractDetailShow = false)"
      >
        <div class="flex-start-center">
          <iframe
            v-if="eleContractDetailShow"
            :src="`${eleContractDetail.path}?token=${auth.token}`"
            class="checkbox"
            style="width: 700px; height: 70vh; overflow: auto"
          />
        </div>
      </a-modal>
      <!-- 删除合同 -->
      <a-modal
        title="删除合同"
        :visible="deleteVisible"
        class="notice-modal"
        width="468px"
        :okButtonProps="{ props: { disabled: loading_delete } }"
        @ok="confirmDelete"
        @cancel="deleteVisible = false"
      >
        <div class="deleteline">
          <p><a-icon type="exclamation-circle" />确定删除该合同？</p>
        </div>
      </a-modal>
    </div>
  </a-spin>
</template>
<script>
import moment from "moment";
import ExportMixin from "xqjr-plugin-common/UploadOrExport/exportMixin";
const mixin = new ExportMixin();
import { mapGetters } from "vuex";
import {
  pageElectronicAndPaperReq,
  exportAllContractReq,
  downloadAttachmentReq,
  deleteContractAndRelationByIdReq,
  empPaperContractsDeleteReq,
  deleteBatchElectronicAndPaperNumberReq,
  contractAppendixReq
} from "./api";
import { mapState } from "vuex";
import { isContainByString } from "@/utils/index";
import { buildColumns, enumerateList, customRenderContractType, customRenderMoment } from "./funcs";
import SummaryBarAll from "./components/summaryBar_all.vue";

export default {
  components: { SummaryBarAll },
  mixins: [mixin],
  props: {
    mode: {
      type: String,
      default: "company"
    }
  },
  data() {
    const columns = buildColumns("all", this.mode === "overview");
    return {
      isContainByString,
      selectedRowList: [],
      columns,
      enumerateList,
      searchForm: this.$form.createForm(this),
      companyName: this.$store.state.hr.companyName,
      updateForm: this.$form.createForm(this, { name: "updateForm" }),
      selectedRowKeys: [],
      contractList: [],
      detailVisible: false,
      confirmLoading: false,
      deleteVisible: false,
      currentContract: {},
      eleContractDetail: {},
      eleContractDetailShow: false,
      selectTypeIndex: 1,
      pagination: {
        pageSize: 10,
        total: 0,
        size: "default",
        current: 1,
        showTotal: (total) => `共 ${total} 条`,
        showQuickJumper: true,
        showSizeChanger: true,
        pageSizeOptions: ["10", "20", "50", "100"]
      },
      spinning: false,
      selectedHead: [],
      updateNameForm: this.$form.createForm(this, {}),
      updateNameVisible: false,
      confirmNameLoading: false,
      putUpdateContractNameId: "",
      // 搜索条件
      contractNameOrNoOrSignNo: "",
      idCard: "",
      fileType: undefined,
      empStatus: undefined,
      publishDateRange: null,
      endDateRange: null,
      signFinishDateRange: null,
      tempSubject: undefined,
      loading_delete: false
    };
  },
  computed: {
    ...mapGetters(["permissions_site"]),
    ...mapState(["auth", "site", "hr"]),
    siteName() {
      return this.auth.siteName;
    },
    targetIds() {
      if (this.mode === "company") {
        return [this.hr.companyId];
      } else {
        if (this.site.selectAllIds && this.site.selectAllIds !== "-1") {
          return Array.from(new Set(this.site.selectAllIds.split(",")));
        }
        return [];
      }
    },
    tempSubjectOptions() {
      return this.targetIds
        .map((item) => ({
          value: item,
          label: this.hr.companyMap[item] ? this.hr.companyMap[item].name : undefined
        }))
        .filter((item) => item.label);
    }
  },
  watch: {
    $route: {
      handler(to, from) {
        if (this.$route.query.immediatelyMaturityCountId) {
          // 消息推送进来
          this.$nextTick(() => {
            this.searchForm.setFieldsValue({
              contractNameOrNoOrSignNo: this.$route.query.contractNameOrNoOrSignNo
            });
          });
          this.selectTypeIndex = Number(this.$route.query.immediatelyMaturityCountId);
          this.searchContract(this.$route.query.contractNameOrNoOrSignNo);
        } else {
          this.selectFunc(1);
        }
      },
      deep: true,
      immediate: true
    },
    targetIds() {
      this.tempSubject = undefined;
      this.selectFunc();
    }
  },
  created() {},
  methods: {
    customRenderContractType,
    customRenderMoment,
    handleTableChange(pagination) {
      this.pagination.current = pagination.current;
      this.pagination.pageSize = pagination.pageSize;
      this.loadContractList();
    },
    searchContract() {
      this.pagination.current = 1;
      this.loadContractList();
    },
    selectFunc(typeIndex) {
      this.pagination.current = 1;
      this.selectedRowKeys = [];
      if (typeIndex || typeIndex === 0) {
        this.selectTypeIndex = typeIndex;
      }
      if (this.$refs.summaryBar) {
        this.$refs.summaryBar.loadData();
      }
      this.loadContractList();
    },
    loadContractList() {
      if (this.spinning) {
        return false;
      }
      this.spinning = true;
      const params = {
        ...this.buildParams(),
        pageNo: this.pagination.current,
        pageSize: this.pagination.pageSize
      };
      pageElectronicAndPaperReq(params)
        .then((res) => {
          this.spinning = false;
          this.contractList = res.data.entities ? res.data.entities : [];
          this.pagination.total = res.data && res.data.entityCount;
        })
        .catch((err) => {
          this.spinning = false;
          console.log(err);
        });
    },
    onSelectChange(selectedRowKeys, tList) {
      this.selectedRowKeys = selectedRowKeys;
      this.selectedRowList = tList;
    },
    check(record) {
      this.detailVisible = true;
      this.checkEleContract(record.id);
    },
    checkEleContract(id) {
      contractAppendixReq({ contractId: id }).then((res) => {
        this.eleContractDetail = res.data[0];
        this.$nextTick(() => {
          this.eleContractDetailShow = true;
        });
      });
    },
    downloadContract(record) {
      if (!record.filePath) return false;
      this.spinning = true;
      const deleteFunc = record.isEntity ? downloadAttachmentReq : deleteContractAndRelationByIdReq;
      deleteFunc({
        siteFileUrls: record.filePath.split(",")
      })
        .then((res) => {
          this.spinning = false;
          if (res.data && res.data.type === "application/json") {
            const reader = new FileReader();
            reader.readAsText(res.data, "utf-8");
            reader.onload = () => {
              const resJson = JSON.parse(reader.result);
              this.$message.error(resJson.msg);
            };
          } else {
            const rspHeaders = res.headers;
            const blob = new Blob([res.data], { type: "application/octet-stream" });
            const link = document.createElement("a");
            try {
              link.download = decodeURI(rspHeaders["content-disposition"].split(";")[1].split("=")[1].replaceAll('"', ""));
            } catch (err) {
              console.log(err);
            }
            link.href = URL.createObjectURL(blob);
            document.body.appendChild(link);
            link.click();
            URL.revokeObjectURL(link.href);
            document.body.removeChild(link);
          }
        })
        .catch((err) => {
          console.log("debug log --> ", err);
          this.spinning = false;
        });
    },
    deleteContract(record) {
      this.currentNotice = record;
      this.deleteVisible = true;
      if (record) {
        this.selectedRowKeys = [];
        this.selectedRowKeys.push(record.id);
      }
    },
    confirmDelete() {
      if (this.contractList.length === this.selectedRowKeys.length && this.pagination.current > 1) {
        this.pagination.current -= 1;
      }
      this.loading_delete = true;
      if (this.selectedRowKeys.length < 1) {
        empPaperContractsDeleteReq(this.currentNotice.id)
          .then(() => {
            this.deleteVisible = false;
            this.loading_delete = false;
            this.$message.success("删除成功");
            if (this.$refs.summaryBar) {
              this.$refs.summaryBar.loadData();
            }
            this.loadContractList();
            this.selectedRowKeys = [];
          })
          .catch(() => {
            this.loading_delete = false;
            this.$message.error("删除失败");
          });
      } else {
        deleteBatchElectronicAndPaperNumberReq(this.selectedRowList.map((item) => ({ id: item.id, isEntity: !!item.isEntity })))
          .then(() => {
            this.deleteVisible = false;
            this.loading_delete = false;
            this.$message.success("删除成功");
            if (this.$refs.summaryBar) {
              this.$refs.summaryBar.loadData();
            }
            this.loadContractList();
            this.selectedRowKeys = [];
          })
          .catch(() => {
            this.loading_delete = false;
            this.$message.error("删除失败");
          });
      }
    },
    buildParams() {
      const params = {
        companyIdList: this.tempSubject ? [this.tempSubject] : this.targetIds,
        userNameOrConNameOrPhone: this.contractNameOrNoOrSignNo,
        idCard: this.idCard,
        type: this.fileType,
        empStatus: this.empStatus,
        startTimeStart:
          this.publishDateRange && this.publishDateRange.length > 0 ? moment(this.publishDateRange[0]).format("YYYY-MM-DD 00:00:00") : null,
        startTimeEnd:
          this.publishDateRange && this.publishDateRange.length > 0 ? moment(this.publishDateRange[1]).format("YYYY-MM-DD 23:59:59") : null,
        endTimeStart: this.endDateRange && this.endDateRange.length > 0 ? moment(this.endDateRange[0]).format("YYYY-MM-DD 00:00:00") : null,
        endTimeEnd: this.endDateRange && this.endDateRange.length > 0 ? moment(this.endDateRange[1]).format("YYYY-MM-DD 23:59:59") : null,
        signFinishDateStart:
          this.signFinishDateRange && this.signFinishDateRange.length > 0
            ? moment(this.signFinishDateRange[0]).format("YYYY-MM-DD 00:00:00")
            : null,
        signFinishDateEnd:
          this.signFinishDateRange && this.signFinishDateRange.length > 0
            ? moment(this.signFinishDateRange[1]).format("YYYY-MM-DD 23:59:59")
            : null
      };
      if (this.selectTypeIndex === 2) {
        params["willExpire"] = true;
      }
      if (this.selectTypeIndex === 3) {
        params["alreadyExpire"] = true;
      }
      if (this.selectTypeIndex === 4) {
        params["exceedDouble"] = true;
      }
      return params;
    },
    selectDownloadType(i) {
      this.exportType = i;
      this.excel_export();
    },
    excel_export() {
      this.spinning = true;
      const contractExcelDTO =
        this.exportType === 1
          ? {
              companyIdList: this.tempSubject ? [this.tempSubject] : this.targetIds,
              exportColumns: this.selectedHead,
              idList: this.selectedRowKeys
            }
          : {
              ...this.buildParams(),
              exportColumns: this.selectedHead
            };
      exportAllContractReq(contractExcelDTO)
        .then((res) => {
          const data = res.data;
          const url = URL.createObjectURL(data);
          const link = document.createElement("a");
          link.href = url;
          link.download = `${this.mode === "overview" ? this.siteName : this.companyName}合同列表详情.xlsx`;
          link.click();
          this.spinning = false;
        })
        .catch((err) => {
          console.log("error log --> ", err);
          this.spinning = false;
        });
    }
  }
};
</script>
<style lang="scss" scoped>
@import "./style.scss";
</style>
